package com.jialanmo.zhihudaily.ui.main;

import com.jialanmo.zhihudaily.Application;
import com.jialanmo.zhihudaily.data.model.Daily;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public final class MainFragmentPresenter implements MainContract.FragmentPresenter {

    private final MainContract.FragmentView mView;

    MainFragmentPresenter(MainContract.FragmentView view) {
        mView = view;
    }

    @Override
    public void start() {
        getLatest();
    }

    @Override
    public void getLatest() {
        mView.setRefreshing(true);
        Application.getApplication(mView.getContext()).getZhihuApi()
                .getLatest()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Daily>() {
                    @Override
                    public void call(Daily daily) {
                        mView.setRefreshing(false);
                        mView.showLatest(daily);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mView.setRefreshing(false);
                        mView.showMessage(throwable.getMessage());
                    }
                });
    }

    @Override
    public void getBefore(int page) {
        String date = new SimpleDateFormat("yyyyMMdd", Locale.CHINESE).format(new Date(System.currentTimeMillis() - page * 1000 * 3600 * 24));
        Application.getApplication(mView.getContext()).getZhihuApi()
                .getBefore(date)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Daily>() {
                    @Override
                    public void call(Daily daily) {
                        mView.showBefore(daily);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mView.showMessage(throwable.getMessage());
                    }
                });
    }
}
